$(document)
  .ready(
    function() {

      // window.onload=function(){
      $.ajax({
        url: "ListDishServlet",
        contenttype: "application/x-www-form-urlencoded;charset=utf-8",
        method: "POST",
        // data:data,
        async: true,
        error: function(XMLHttpRequest, textStatus,
          errorThrown) {
          alert('访问网络失败！' + errorThrown);
        },
        success: function(data) {
          var merchant = data.merchant;
          console.log(data);
          var jsonList = data;
          jsonList.dishes
            .forEach(function(item, index,
              array) {
              var dName = item["dName"];
              var dPrice = item["dPrice"];
              var dImageURL = "ImageLoader?path="+item["dImageURL"];
              var dId = item["dId"];
              $("#dishPanel")
              .append(
                  "<div class='col-md-3'><div class='thumbnail' style=\"margin-top:20px;height:95px;\"><img src='"+dImageURL+"' style=\"float:left;width:80px;height:80px;\"><div class='caption'><p>" +"￥"+
                  dPrice +
                  "</p><div class=\"merchant_merchanttitle\">"+dName+"</div><a id='deleteId"+ dId +"' style=\"float:left;\">delete</a><a style='float:right;' id='update"+dId+"' href='' data-toggle=\"modal\"data-target=\"#updateDish\">update</a></div></div></div>");
            $("#update"+dId).on("click", function(event) {
          	  $.ajax({
          		  url:"QueryDishServlet?dId=" + dId,
          		  mehtod:"GET",
          		  success:function(data) {
          			  console.log(data);
          			  var dish = data.dish;
          			$("#dish_did").val(dish.dId);
          			  $("#dish_name").val(dish.dName);
          			  $("#dish_price").val(dish.dPrice);
          			  $("#image").attr("src", dImageURL);
          			  data.dishtype.forEach(function(item, index, arr) {
          				  if(item.pId === dish.pId) {
          					  $("#updateDishType").append("<option selected='selected' value='"+ item.pId +"'>" + item.pname + "</option>")
          				  } else {
          					  $("#updateDishType").append("<option value='"+ item.pId +"'>" + item.pname + "</option>");
          				  }
          			  });
          		  }
          	  });
            });
              $("#deleteId"+dId).on("click", function(event) {
            	  $.ajax({
            		  url:"DeleteDishServlet?dId=" + dId,
            		  method:"GET",
            		  success:function(data) {
            			  console.log(data);
            			  window.location.href=window.location.href;
            		  }
            	  });
              })
            });
          	
          jsonList.dishtype.forEach(function(item, index,
            array) {
            var pId = item["pId"];
            var pname = item["pname"];
            $("#dishTypes")
              .append(
                "<li id='" +
                pId +
                "' class='list-group-item'><button class='menu-item-left'> <span class='glyphicon glyphicon-triangle-right'>" +
                pname +
                "</span></button></li>");
            $("#"+pId).on("click", function(event) {
            	$.ajax({
            		url:"ListDishServlet?dType=" + pId,
            		method:"GET",
            		success:function(data) {
            			$("#dishPanel").html("");
            			data.dishes.forEach(function(item, index, arr) {
            				var dName = item["dName"];
            	             var dPrice = item["dPrice"];
            	             var dImageURL = "ImageLoader?path="+item["dImageURL"];
            	              var dId = item["dId"];
            	              $("#dishPanel")
            	              .append(
                  "<div class='col-md-3'><div class='thumbnail' style=\"margin-top:20px;height:95px;\"><img src='"+dImageURL+"' style=\"float:left;width:80px;height:80px;\"><div class='caption'><p>" +"￥"+
                  dPrice +
                  "</p><div class=\"merchant_merchanttitle\">"+dName+"</div><a id='deleteId"+ dId +"' style=\"float:left;\">delete</a><a style='float:right;'id='update"+ dId +"' href='' data-toggle=\"modal\"data-target=\"#updateDish\">update</a></div></div></div>");
            	              $("#update"+dId).on("click", function(event) {
            	            	  $.ajax({
            	            		  url:"QueryDishServlet?dId=" + dId,
            	            		  mehtod:"GET",
            	            		  success:function(data) {
            	            			  var dish = data.dish;
            	            			  console.log(dish.dId);
            	            			  $("#dish_did").val(dish.dId);
            	            			  $("#dish_name").val(dish.dName);
            	            			  $("#dish_price").val(dish.dPrice);
            	            			  $("#image").attr("src", dImageURL);
            	            			  data.dishtype.forEach(function(item, index, arr) {
            	            				  if(item.pId === dish.pId) {
            	            					  $("#updateDishType").append("<option selected='selected' value='"+ item.pId +"'>" + item.pname + "</option>")
            	            				  } else {
            	            					  $("#updateDishType").append("<option value='"+ item.pId +"'>" + item.pname + "</option>");
            	            				  }
            	            			  });
            	            			  
            	            		  }
            	            	  });
            	              });
            	              $("#deleteId"+dId).on("click", function(event) {
            	            	  $.ajax({
            	            		  url:"DeleteDishServlet?dId=" + dId,
            	            		  method:"GET",
            	            		  success:function(data) {
            	            			  console.log(data);
            	            			  window.location.href=window.location.href;
            	            		  }
            	            	  });
            	              })
            			})
            		}
            	})
            });
            
            $("#selDishType").append("<option value='"+ pId +"'>" + pname + "</option>");
            
          });


          $("#merchant")
           $("#merchant")
          .append(
            "<img id='MerImg' src='ImageLoader?path=" +
            merchant.imageUrl +
            "' style='width:70px;height:70px;'>");
        $("#merchantName").append("<a href='#'>" +
            merchant.mName +
            "</a>"
         );
          $("#addForm").append("<input type='hidden' name='mid' value='" + merchant.mId + "'>");
          $("#updateForm").append("<input type='hidden' name='mid' value='" + merchant.mId + "'>");

          //          deteleDish();
        }
      });
      // }
//      function deteleDish() {
//        var a = $("a[id='deteleId']").click(function() {
//          var dId = $('#dId').val();
//          var data = {
//            dId: dId
//          }
//          $.ajax({
//            url: "DeleteDishServlet",
//            contenttype: "application/x-www-form-urlencoded;charset=utf-8",
//            method: "POST",
//            data: data,
//            async: true,
//            error: function(XMLHttpRequest, textStatus,
//              errorThrown) {
//              alert('访问网络失败！' + errorThrown);
//            },
//            success: function(data) {
//
//              alert('删除成功')
//            }
//          });
//        })
//      }

      
      function addDish(merchant) {
        var btn = $("#addBtn");
        btn.on("click", function(event) {
          var dName = $('#newDishName').val();
          var dPrice = $('#newDishPrice').val();
          var imagepath = $('#newDishImg').val();
          var mId = merchant.mId;
          var pId = $("selDishType").val();
          console.log(mId);
          var data = {
            dName: dName,
            dPrice: dPrice,
            imagepath: imagepath,
            mid: mId,
            pId:pId
          }
          console.log(data);
          $.ajax({
            method: "POST",
            url: "AddDishServlet",
            error: function() {
              alert('error');
            },
            data: data,
            success: function(respData) {
              console.log(respData);
              $("#dishPanel").html("");
              respData.dishes.forEach(function(item, index, arr) {
  				var dName = item["dName"];
  	             var dPrice = item["dPrice"];
  	             var dImageURL = item["dImageURL"];
  	              var dId = item["dId"];
  	              var img = $('#dishImg');
  	              img.attr("src", dImageURL);
  	              $("#dishPanel")
  	                .append(
  	                  "<div class='col-md-3'><div class='thumbnail' style=\"margin-top:20px;\"><img id=\"dishImg\" style=\"float:left;width:70px;height:70px;\"><div class='caption'><p>" +
  	                  dPrice +
  	                  "</p><a id='deleteId'>delete</a><a href=''data-toggle=\"modal\"data-target=\"#updateDish\">update</a></div></div></div>");
  			})
            }

          });
        });
      }

      function queryDishes() {
        var mId = $('#mId').val();
        var pId = "";

        function getPId() {
          $("#dishTypes li").each(function(i) {
            var This = $(this);

            This.click(function() {

              if (This.index() == 0) {
                pId = "000"; // all
              }
              if (This.index() == 1) {
                pId = "003"; // 川菜
              }
              if (This.index() == 2) {
                pId = "001"; // 粤菜
              }
              if (This.index() == 3) {
                pId = "002"; // 湘菜
              }
              if (This.index() == 4) {
                pId = "004"; // 甜食
              }
            });
          });
        };

        var data = {
          mId: mId,
          pId: pId
          // dType: dataTos
        };

 
        $
          .ajax({
            url: "QueryDishServlet",
            contenttype: "application/x-www-form-urlencoded;charset=utf-8",
            method: "POST",
            data: data,
            async: true,
            error: function(XMLHttpRequest,
              textStatus, errorThrown) {
              alert('访问网络失败！' + errorThrown);
            },
            success: function(data) {
              var jsonList = JSON.parse(data);
              jsonList
                .forEach(function(item, index,
                  array) {
                  var dName = item["dName"];
                  var dPrice = item["dPrice"];
                  var dImageURL = item["dImageURL"];
                  var img = $('#dishImg');
                  img.attr("src", dImageURL);

                  $("#dishPanel")
                    .append(
                      "<div class='col-md-3'><div class='thumbnail' style=\"margin-top:20px;\"><img id=\"dishImg\" style=\"float:left;width:70px;height:70px;\"><div class='caption'><p>" +
                      dPrice +
                      "</p><a href='DeleteDishServlet?dId=" +
                      dId +
                      "'>delete</a><a href=''data-toggle=\"modal\"data-target=\"#updateDish\">update</a></div></div></div>");

                })
            }

          });
    

      }

      function updateMerchant() {
        var btn = $("#user_btn");
        btn.on("click", function(event) {
          var uname = $("#mer_name").val();
          var upassword = $("#mer_pass").val();
          var uaddress = $("#mer_address").val();
          //商家头像的获取
          var imagepath = $("#input_ico").val();
          
          var data = {
            name: uname,
            password: upassword,
            address: uaddress,
            imagepath: imagepath
          };

          $.ajax({
            method: "POST",
            url: "UpdateMerInfoServlet",
            error: function() {
              alert('error');
            },
            data: data,
            success: function(respData) {
              var jsonList = JSON.parse(respData);
              jsonList.forEach(function(item, index,
                array) {
                var mName = item["mName"];
                var imageUrl = item["imageUrl"];
                $('#mId').val(mName);
                $('#MerImg').val(imageUrl);
                alert(respData);
                console.log(respData);
              });
            }
          });
        });
      }
    })